import 'dart:collection';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/checkin/checkinmodel.dart';
import 'package:opene/utils/ImageUtils.dart';
import 'package:scan_gun/scan_gun.dart';
import 'package:toast/toast.dart';

import 'tallylpnscreen.dart';
import 'tallymodel.dart';

class CustomDialog extends StatefulWidget {
  TallyQr tally;
  List<TallyDetail> tallyDetails = new List();

  CustomDialog({this.tally, this.tallyDetails});

  @override
  _CustomDialogState createState() => _CustomDialogState(tally: tally, tallyDetails: this.tallyDetails);
}

class _CustomDialogState extends State<CustomDialog> {
  TallyQr tally;
  List<TallyDetail> tallyDetails = new List();

  _CustomDialogState({this.tally, this.tallyDetails});

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12.0),
      ),
      child: Padding(
        padding: const EdgeInsets.only(top: 15, left: 15, right: 15),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text("Detail(${tally.container_no})", style: MyAppTheme.title),
            SizedBox(height: 16.0),
            Row(
              children: [
                Expanded(
                    flex: 2,
                    child: Text(
                      'SKU',
                      style: MyAppTheme.text,
                    )),
                Expanded(flex: 1, child: Text('Tallied', style: MyAppTheme.text)),
                Expanded(flex: 1, child: Text('lpnQTY', style: MyAppTheme.text)),
                SizedBox(width: 20.0),
              ],
            ),
            Flexible(
              fit: FlexFit.loose,
              child: setListView(),
            ),
            // Expanded(
            //   child: setListView(),
            // ),
            // setListView(),
            // SizedBox(height: 5.0),
            Row(
              children: <Widget>[
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Close',
                        style: MyAppTheme.title,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    )),
              ],
            ),
          ],
        ),
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      shrinkWrap: true,
      // physics: NeverScrollableScrollPhysics(),
      itemCount: tallyDetails == null ? 0 : tallyDetails.length,
      itemBuilder: (context, index) {
        TallyDetail tallyDetail = tallyDetails[index];
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                    flex: 2,
                    child: Text(
                      tallyDetail.sku,
                      style: MyAppTheme.text,
                    )),
                Expanded(flex: 1, child: Text('${tallyDetail.tallyQty}', style: MyAppTheme.text)),
                Expanded(flex: 1, child: Text('${tallyDetail.lpnQty}', style: MyAppTheme.text)),
                GestureDetector(
                  onTap: () {
                    setState(() {
                      if (tallyDetail.list == null || tallyDetail.list.length == 0) {
                        getLpnQtyList(tally.notifyId, tallyDetail, index);
                        return;
                      }
                      tallyDetail.click = !tallyDetail.click;
                    });
                  },
                  child: Icon(
                    tallyDetail.click ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                    size: 20,
                    color: MyAppTheme.nearlyBlue,
                  ),
                ),
              ],
            ),
            Visibility(visible: tallyDetail.click ? true : false, child: setListViewItem(tallyDetail.list)),
            // Expanded(
            //   child: Visibility(visible: tally.click, child: setListViewItem(tally.list)),
            // ),
            Divider(),
          ],
        );
      },
    );
  }

  ListView setListViewItem(List<Lpns> list) {
    return ListView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: list == null ? 0 : list.length,
      itemBuilder: (context, index) {
        Lpns lpnBean = list[index];
        return Row(
          children: [
            SizedBox(
              width: 10,
            ),
            Expanded(
                flex: 2,
                child: Text(
                  Utils.getStringisEmpty(lpnBean.lpn),
                  style: MyAppTheme.test12,
                )),
            Expanded(flex: 1, child: Text('${lpnBean.inventory}', style: MyAppTheme.test12)),
            Visibility(
              visible: Utils.isEmpty(lpnBean.type) ? false : (lpnBean.type == 'good' ? false : true),
              child: Image.asset(
                'assets/images/home/ic_home_damage.png',
                width: 20,
                height: 20,
              ),
            ),
            Visibility(
              visible: Utils.isEmpty(lpnBean.type) ? true : (lpnBean.type == 'good' ? true : false),
              child: SizedBox(
                width: 20,
              ),
            ),
          ],
        );
      },
    );
  }

  void getLpnQtyList(int id, TallyDetail tallyDetail, int position) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }

    Map<String, dynamic> map = new HashMap();
    map["warehousingNotifyId"] = id;
    map["sku"] = tallyDetail.sku;
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.getTallySkuDetail, params: map);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        tallyDetail.list = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => Lpns.fromJson(userJson)).toList());
        tallyDetail.click = true;
        tallyDetails[position] = tallyDetail;
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
}

//======================================

class CompleteDialog extends StatefulWidget {
  int id;

  CompleteDialog({this.id});

  @override
  _CompleteDialogState createState() => _CompleteDialogState(id: this.id);
}

class _CompleteDialogState extends State<CompleteDialog> {
  final TextEditingController textEditingController = TextEditingController();
  int id;

  _CompleteDialogState({this.id});

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12.0),
      ),
      child: Padding(
        padding: const EdgeInsets.only(top: 15, left: 15, right: 15),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text("Are you sure the tallying including good and damage is completed?", style: MyAppTheme.title),
            SizedBox(height: 5.0),
            Container(
              margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 0),
              width: double.infinity,
              child: ConstrainedBox(
                constraints: BoxConstraints(maxHeight: 40),
                child: TextField(
                  controller: textEditingController,
                  textInputAction: TextInputAction.search,
                  onSubmitted: (String text) {
                    print('Searching for $text');
                  },
                  // autofocus: true,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: MyAppTheme.nearlyBlue,
                      ),
                      borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                      // 设置焦点之外的边框颜色
                      borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                      // 设置焦点时的边框颜色
                      borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                    ),
                    hintText: "enter password",
                    filled: true,
                    fillColor: MyAppTheme.white,
                    //隐藏下划线
                    //border: InputBorder.none,
                    hintStyle: TextStyle(color: Colors.grey),
                    contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                  ),
                  onChanged: (text) {},
                ),
              ),
            ),
            Row(
              children: <Widget>[
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Close',
                        style: MyAppTheme.title,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    )),
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Confirm',
                        style: MyAppTheme.titlenearlyBlue16,
                      ),
                      onPressed: () {
                        if (Utils.isEmpty(textEditingController.text)) {
                          ToastContext().init(context);
                          Toast.show('enter password', duration: Toast.lengthShort, gravity: Toast.bottom);
                          return;
                        }
                        //            if (!password_default.equals(password)) {
                        //                dialogBinding.tvPasswordHint.setText("wrong password");
                        //                return;
                        //            }
                        tallyComplete(id);
                      },
                    )),
              ],
            ),
          ],
        ),
      ),
    );
  }

  void tallyComplete(int id) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context, title: "Complete...");
    } catch (e) {
      e.toString();
    }

    TallyFinishQr tallyFinishQr = new TallyFinishQr(id);
    String json = jsonEncode(tallyFinishQr);
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.tallyComplete, method: BaseMethod.post, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      Navigator.pop(context, true);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
}


//=====================================================

class CheckSkuDialog extends StatefulWidget {
  TallyQr tally;
  bool smallItem;

  CheckSkuDialog({this.tally, this.smallItem});

  @override
  _CheckSkuDialogState createState() => _CheckSkuDialogState(tallyQr: tally, smallItem: this.smallItem);
}

class _CheckSkuDialogState extends State<CheckSkuDialog> {
  TallyQr tallyQr;
  bool smallItem;

  _CheckSkuDialogState({this.tallyQr, this.smallItem});

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12.0),
      ),
      child: Padding(
        padding: const EdgeInsets.only(top: 15, left: 15, right: 15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text(smallItem?"Small items!":"Large items!", style: MyAppTheme.title),
            SizedBox(height: 16.0),
            Image.asset(
              smallItem?'assets/images/ic_small_cargo.png':'assets/images/ic_large_cargo.png',
              width: 100,
              height: 100,
            ),
            Row(
              children: <Widget>[
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Close',
                        style: MyAppTheme.title,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    )),
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Confirm',
                        style: MyAppTheme.titlenearlyBlue16,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop('ok');
                      },
                    )),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

//=====================================================

class SkuExceedDialog extends StatefulWidget {
  SkuExceed skuExceed;

  SkuExceedDialog({this.skuExceed});

  @override
  _SkuExceedDialogState createState() => _SkuExceedDialogState(skuExceed: this.skuExceed);
}

class _SkuExceedDialogState extends State<SkuExceedDialog> {
  SkuExceed skuExceed;

  _SkuExceedDialogState({this.skuExceed});

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12.0),
      ),
      child: Padding(
        padding: const EdgeInsets.only(top: 15, left: 15, right: 15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text("Warning", style: MyAppTheme.title),
            SizedBox(height: 16.0),
            Text( "Compared with the forecast the following values differ significantly:", style: MyAppTheme.text),
            SizedBox(height: 5.0),
            Text( "${skuExceed.isLength ? "length " : ""}${skuExceed.isWidth ? "width " : ""}${skuExceed.isHeight ? "height " : ""}${skuExceed.isWeight ? "weight " : ""}", style: MyAppTheme.textred14),
            SizedBox(height: 16.0),
            Row(
              children: <Widget>[
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Close',
                        style: MyAppTheme.title,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    )),
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Confirm',
                        style: MyAppTheme.titlenearlyBlue16,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop('ok');
                      },
                    )),
              ],
            ),
          ],
        ),
      ),
    );
  }
}